#!/bin/bash

#
# @date:2021-10-10
# @author:deep as the sea 
# @orgnization:doitedu
# @desc:app端行为日志数据文件加载入库
#


export HIVE_HOME=/opt/apps/hive-3.1.2

dt=$(date -d'-1 day' +%Y-%m-%d)

if [ $1 ];then
echo "运行脚本，传入了指定的日期，将导指定日期的数据"
dt=$1
fi

dt_pre=$(date -d"${dt} -1day" +%Y-%m-%d)

${HIVE_HOME}/bin/hive -e "
--set mapreduce.framework.name=local;
add jar /opt/apps/hive-3.1.2/hcatalog/share/hcatalog/hive-hcatalog-core-3.1.2.jar;
INSERT INTO TABLE dim.dev_acc_bind_w PARTITION(dt='${dt}')

SELECT
     nvl(o1.device_id,o2.device_id) as device_id,
     nvl(o1.account,o2.account)    as account,
     case 
      when o1.device_id is not null and o2.device_id is not null then o1.weight+o2.weight
      when o1.device_id is not null and o2.device_id is     null then o1.weight
      else o2.weight * 0.5
     end  as weight,
     nvl(o1.last_login_time,o2.last_login_time) as last_login_time
FROM

(  -- T日行为事件明细会话聚合数据
   SELECT 
      deviceid as device_id,
      account,
      count(distinct sessionid)*100 as weight,
      max(\`timestamp\`) as last_login_time
   FROM ods.mall_app_log_dtl 
   WHERE dt='${dt}' AND account is not null  AND account!=''  
   GROUP BY deviceid,account
) o1
   
FULL JOIN   

(   -- 绑定权重表T-1日数据
   SELECT
     device_id
     ,account
     ,weight           
     ,last_login_time  
   FROM dim.dev_acc_bind_w
   WHERE dt='${dt_pre}'
) o2
ON o1.device_id=o2.device_id AND o1.account=o2.account
"


if [ $? -eq 0 ];then
  echo "任务成功：设备账号绑定权重表更新计算成功"
  echo "目标表分区：dim.dev_acc_bind_w  partition(dt='${dt}')"
  echo "任务成功：设备账号绑定权重表更新计算成功；目标表分区：dim.dev_acc_bind_w  partition(dt='${dt}')" | mail -s '多易集团,商城业务数据部，HIVE任务成功通知' 83544844@qq.com
  exit 0
else
  echo "任务失败：设备账号绑定权重表更新计算失败"
  echo "目标表分区：dim.dev_acc_bind_w  partition(dt='${dt}')"
  echo "任务失败：设备账号绑定权重表更新计算失败；目标表分区：dim.dev_acc_bind_w  partition(dt='${dt}')" | mail -s '多易集团,商城业务数据部，HIVE任务失败通知' 83544844@qq.com
  exit 0
fi  
